package com.miao.service.impl;

import com.miao.mapper.MediaFilesMapper;
import com.miao.mapper.MediaProcessHistoryMapper;
import com.miao.pojo.MediaFiles;
import com.miao.pojo.MediaProcess;
import com.miao.mapper.MediaProcessMapper;
import com.miao.pojo.MediaProcessHistory;
import com.miao.service.IMediaProcessService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-02-03
 */
@Service
public class MediaProcessServiceImpl extends ServiceImpl<MediaProcessMapper, MediaProcess> implements IMediaProcessService {
    @Autowired
    private MediaProcessMapper mediaProcessMapper;
    @Autowired
    private MediaFilesMapper mediaFilesMapper;
    @Autowired
    private MediaProcessHistoryMapper mediaProcessHistoryMapper;

    //根据当前分片获取需要进行格式转化的视频
    @Override
    public List<MediaProcess> getWaitTransList(int sharedTotal, int sharedIndex, int count) {
       return mediaProcessMapper.getListOfProcessOfXll(sharedTotal, sharedIndex, count);
    }

    //开启任务，抢锁
    @Override
    public int startTask(Long id){
        return mediaProcessMapper.startTask(id);
    }

    //更新处理结果
    @Transactional
    @Override
    public void saveProcessFinish(Long taskId, String status, String fileID, String errorMsg, String url) {
        //目标任务
        MediaProcess mediaProcess = mediaProcessMapper.selectById(taskId);
        if(mediaProcess == null){
            return;
        }
        //如果执行失败
        if(status.equals("3")){
            mediaProcess.setStatus("3");
            mediaProcess.setErrormsg(errorMsg);
            mediaProcess.setFailCount(mediaProcess.getFailCount() + 1);
            mediaProcessMapper.updateById(mediaProcess);
            return;
        }
        //任务执行成功
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileID);
        //更新url
        mediaFiles.setUrl(url);
        mediaFilesMapper.updateById(mediaFiles);

        mediaProcess.setStatus("2");
        mediaProcess.setFinishDate(LocalDateTime.now());
        mediaProcess.setUrl(url);
        mediaProcessMapper.updateById(mediaProcess);

        //插入到历史记录表
        MediaProcessHistory mediaProcessHistory = new MediaProcessHistory();
        BeanUtils.copyProperties(mediaProcess, mediaProcessHistory);
        mediaProcessHistoryMapper.insert(mediaProcessHistory);


        //删除当前
        mediaProcessMapper.deleteById(taskId);

    }
}
